package main

import (
	"./controller"
	"html/template"
	"log"
	"net/http"
)

/**
 * 渲染视图
 */
func renderView() {

	tpl, err := template.ParseGlob("view/**/*")
	if err != nil {
		log.Fatal(err.Error())
	}

	for _, item := range tpl.Templates() {

		tplName := item.Name()
		http.HandleFunc(tplName, func(writer http.ResponseWriter, request *http.Request) {
			err = item.ExecuteTemplate(writer, tplName, nil)
			if err != nil {
				log.Fatal(err.Error())
			}
		})
	}
}

func main() {

	// 登录
	http.HandleFunc("/user/login", controller.Login)
	// 注册
	http.HandleFunc("/user/register", controller.Register)
	// 聊天
	http.HandleFunc("/chat", controller.Chat)
	// 加好友
	http.HandleFunc("/contact/addFriend", controller.AddFriend)
	// 获取好友列表
	http.HandleFunc("/contact/getFriends", controller.GetFriendList)

	// 提供静态资源目录
	http.Handle("/", http.FileServer(http.Dir(".")))
	// 渲染页面
	renderView()
	// 监听
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err.Error())
	}
}
